package com.gmail.shazi199.satoriex;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;

import com.gmail.shazi199.satoriex.stage.BaseStage;
import com.gmail.shazi199.satoriex.stage.TitleStage;
import com.gmail.shazi199.satoriex.utils.TextReader;

public class App {

    private static final Log LOGGER = LogFactory.getLog(App.class);

    private static App app;

    private BaseStage stage;

    private boolean running = true;

    public void start() {
        while (!Display.isCloseRequested() && running) {
            this.stage.update();
            this.stage.draw();
            Display.update();
            Display.sync(60);
        }
        Display.destroy();
    }

    public void exit() {
        running = false;
    }

    public void init() {
        try {
            Display.setDisplayMode(new DisplayMode(640, 480));
            Display.create();
            Display.setTitle(TextReader.getString("title.name"));
        } catch (LWJGLException e) {
            LOGGER.error("Create Windows Fail.", e);
            App.getApp().exit();
        }
        this.stage = new TitleStage();
        initGL();
    }

    public void initGL() {
        GL11.glEnable(GL11.GL_TEXTURE_2D);

        GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

        // enable alpha blending
        GL11.glEnable(GL11.GL_BLEND);
        GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);

        GL11.glViewport(0, 0, 640, 480);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);

        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        GL11.glOrtho(0, 640, 480, 0, 1, -1);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
    }

    public BaseStage getStage() {
        return stage;
    }

    public void setStage(BaseStage stage) {
        this.stage = stage;
    }

    public static App getApp() {
        return app;
    }

    public static void main(String[] args) {
        app = new App();
        app.init();
        app.start();
    }
}
